<template>
  <div class="container">
    <h1>桂林电子科技大学科技园</h1>
    <h2>退 租 审 批 表</h2>

    <el-form :model="form" :rules="rules" ref="formRef" label-width="150px" style="display: flex; flex-wrap: wrap">
      <el-card>
        <!-- 企业/团队信息 -->
        <el-row :gutter="20" style="width: 100%">
          <el-col :span="12">
            <el-form-item label="企业:" prop="enterpriseName">
              <el-input v-model="form.enterpriseName" placeholder="请输入企业"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="申请时间:" prop="applicationDate">
              <el-date-picker
                v-model="form.applicationDate"
                type="date"
                placeholder="选择日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 房号及卡座号、经办人、联系方式 -->
        <el-row :gutter="20" style="width: 100%">
          <el-col :span="8">
            <el-form-item label="房号:" prop="roomNumber">
              <el-input v-model="form.roomNumber" placeholder="请输入房号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="经办人:" prop="contactPerson">
              <el-input v-model="form.contactPerson" placeholder="请输入经办人"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系方式:" prop="contactMethod">
              <el-input v-model="form.contactMethod" placeholder="请输入联系方式"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="申请退出日期:" prop="exitDate">
            <el-date-picker
              v-model="form.exitDate"
              type="date"
              placeholder="选择日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 100%"
            ></el-date-picker>
          </el-form-item>

        <!-- 退出原因 -->
        <el-form-item label="退租原因:" prop="exitReason">
          <el-input
            placeholder="请输入退出原因"
            v-model="form.exitReason"
            :style="{ resize: 'none' }"
          >
          </el-input>
        </el-form-item>

      </el-card>

      <el-card>
        <div slot="header" class="header">退款账户明细</div>
        <el-form-item label="户名:" prop="refundAccountName">
          <el-input v-model="form.refundAccountName" placeholder="请输户名"></el-input>
        </el-form-item>
        <el-form-item label="账号:" prop="refundAccountNumber">
          <el-input v-model="form.refundAccountNumber" placeholder="请输入账号"></el-input>
        </el-form-item>
        <!-- 开户银行 -->
        <el-form-item label="开户行:" prop="refundBank">
          <el-input v-model="form.refundBank" placeholder="请输入开户行"></el-input>
        </el-form-item>
      </el-card>

      <el-card>
        <div slot="header" class="header">承诺书
          <el-button type="primary" @click="handleDownloadCommitment">下载承诺书</el-button>
          <el-button type="success" @click="handleDownloadFullForm">下载完整申请表</el-button>
        </div>
        <div class="commit">
          <p>
            &#12288;&#12288;本公司承诺以上填报内容真实有效，截止至申请退租日期承诺做到以下两点：1、清空场地
            内所有物品并将原租用场地打扫干净；2、将租用场地的钥匙交给科技园相关负责老师。<br />
            &#12288;&#12288;如超过申请退租日期 1
            个月仍未将原租用场地清空，则视为自动放弃场地内的所有物品的
            所有权，桂林电子科技大学科技园有权对其进行处置。<br />
            &#12288;特此承诺。
          </p>
          <!-- 申请人签名 -->
          <el-form-item label="承诺人(公司法人):">
            <el-input disabled placeholder=""></el-input>
          </el-form-item>

          <!-- 申请人签名日期 -->
          <el-form-item label="日期:">
          </el-form-item>
        </div>
      </el-card>

      <!-- 科技园审批 -->
      <el-card>
        <div slot="header" class="header">科技园审批 (以下内容由科技园填写)</div>
        <!-- 履约保证金 -->
        <el-form-item label="履约保证金:">
          <el-input disabled v-model="form.deposit" placeholder="请输入保证金"></el-input>
        </el-form-item>
        <!-- 应缴款 -->
        <el-form-item label="应缴费:">
          <el-input disabled v-model="form.rentalFee" placeholder="请输入房屋租凭费"></el-input>
        </el-form-item>
        <!-- 应退款 -->
        <el-form-item label="应退款:">
          <el-input disabled v-model="form.refundAmount" placeholder="请输入退款金额"></el-input>
        </el-form-item>
        <!-- 需补交款 -->
        <el-form-item label="需补缴款:">
          <el-input disabled v-model="form.additionalPayment" placeholder="请输入需补缴款"></el-input>
        </el-form-item>

        <!-- 经手人 -->
        <el-form-item label="经手人:">
          <el-input disabled v-model="form.handler" placeholder="请输入经手人"></el-input>
        </el-form-item>

        <!-- 办公室主任核签 -->
        <el-form-item label="办公室主任核签:">
          <el-input
            disabled
            v-model="form.officeDirectorSignature"
            placeholder="请输入办公室主任核签"
          ></el-input>
        </el-form-item>
        <!-- 部门负责人意见 -->
        <el-form-item label="部门负责人意见:">
          <el-input
            disabled
            type="textarea"
            :rows="3"
            v-model="form.departmentHeadSignature"
            placeholder="请输入部门负责人意见"
          ></el-input>
        </el-form-item>

        <!-- 提交按钮 -->
        <el-form-item>
          <el-button type="primary" @click="onSubmit">提交</el-button>
          <el-button @click="saveDraft">保存草稿</el-button>
        </el-form-item>
      </el-card>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import {
  downloadCommitment, editexitApplicationForm,
  exitApplicationForm,
  exitCreateSpaceForm,
  getexitApplicationForm
} from '@/api/personal-center';
import { ElMessage } from 'element-plus';
import {onMounted, reactive, ref} from 'vue';
import {type FormInstance, type FormRules,ElLoading } from 'element-plus';
import {useRoute} from "vue-router";
import router from "@/router";
import type { AjaxResult } from '@/types/resultTypes';
const route = useRoute();
const totalRecord = ref(0);//用来标记用户是不是第一次提交 0，1表示是从我的退出填报中点击编辑过来的
const formRef = ref<FormInstance>();

const form = reactive({
  status: 0,
  enterpriseName: '', // 企业名称
  applicationDate: '', // 申请日期，默认当前时间
  roomNumber: '', // 房号及卡座号
  contactPerson: '', // 经办人
  contactMethod: '', // 联系方式
  exitReason: '', // 退出原因
  exitDate: '', // 退出日期，默认当前时间
  refundAccountName: '', // 退款账户名
  refundAccountNumber: '', // 退款账号
  refundBank: '', // 开户银行
  applicantSignature: '', // 申请人签名
  commitmentDate: '', // 承诺日期，默认当前时间
  deposit: 0.0, // 已缴纳保证金金额
  rentalFee: 0.0, // 租金费用
  refundAmount: 0.0, // 退款金额
  additionalPayment: 0.0, // 额外支付金额
  handler: '', // 经手人
  officeDirectorSignature: '', // 办公室主任签名
  departmentHeadSignature: '', // 部门负责人签名
});

const rules = ref<FormRules>({
  enterpriseName: [
    { required: true, message: '请输入企业名称', trigger: 'blur' }
  ],
  applicationDate: [
    { required: true, message: '请选择申请日期', trigger: 'change' }
  ],
  roomNumber: [
    { required: true, message: '请输入房号', trigger: 'blur' }
  ],
  contactPerson: [
    { required: true, message: '请输入经办人', trigger: 'blur' }
  ],
  contactMethod: [
    { required: true, message: '请输入联系方式', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  exitReason: [
    { required: true, message: '请输入退租原因', trigger: 'blur' },
    { min: 10, message: '退租原因不能少于10个字符', trigger: 'blur' }
  ],
  refundAccountName: [
    { required: true, message: '请输入退款账户名', trigger: 'blur' }
  ],
  refundAccountNumber: [
    { required: true, message: '请输入退款账号', trigger: 'blur' },
    { pattern: /^\d{16,19}$/, message: '请输入正确的银行账号', trigger: 'blur' }
  ],
  refundBank: [
    { required: true, message: '请输入开户行', trigger: 'blur' }
  ],
  exitDate:[
      { required: true, message: '请选择退租日期', trigger: 'change' }
  ]
});
// 获取用户未提交的报表数据
const getUserDraft = async (id: number)=> {
  try{
    // // 确保ID是BigInt类型
    // let bigIntId;
    //   bigIntId = BigInt(id);
    const res = await getexitApplicationForm(id) as unknown as AjaxResult<any>;
    if (res.code === 200) {
      // if (res.data.exitReason) {
      //   res.data.exitReason = res.data.exitReason.split(','); // 假设后端使用逗号分隔
      // }
      Object.assign(form, res.data);
    }
  } catch (error) {
    console.error('获取报表数据失败:', error);
    ElMessage.error('获取报表数据失败');
  }
};

const onSubmit = () => {
  if (!formRef.value) return;

  formRef.value.validate((valid) => {
    if (valid) {
      if (totalRecord.value === 0) {
        form.status = 1;
        exitApplicationForm(form).then((res) => {
          ElMessage.success({ message: '提交成功', type: 'success' });
          router.push('/personal-center/graduation-or-exit/my-exit');
      }).catch(() => {
        ElMessage.error('提交失败');
      });
      }else{
          form.status = 1;
          //totalRecord.value === 1表示从我的退出点进来的
            editexitApplicationForm(form).then((res) => {//更新状态
            ElMessage.success({message: '提交成功', type: 'success'});
            router.push('/personal-center/graduation-or-exit/my-exit');
          });
      }
    }

      else {
      ElMessage.error('表单信息有误或未填写完整');
    }
  });
};

// const handleDownloadCommitment = () => {
//   downloadCommitment().then((res) => {
//
//     ElMessage.success({ message: '下载成功', type: 'success' });
//   }).catch(() => {
//     ElMessage.error('下载失败');
//   });
// }

// 下载承诺书 新修改代码 不采用响应式方式
// 使用blob二进制流好像有点问题 文件类型为undefine 保存文件出错 如有新解决方案可替换以下代码
const handleDownloadCommitment = () => {
  // 显示下载开始提示
  const loadingMessage = ElMessage({
    message: '正在准备下载...',
    type: 'info',
    duration: 0 // 不会自动关闭
  });

  // 直接创建下载链接
  const downloadUrl = '/api/kjy/static/book.docx';

  // 创建隐藏的 <a> 元素
  const link = document.createElement('a');
  link.href = downloadUrl;

  // 添加文件名属性
  link.setAttribute('download', '承诺书.docx');

  // 添加到文档中
  document.body.appendChild(link);

  // 设置超时检测
  const timeoutId = setTimeout(() => {
    ElMessage.closeAll();
    ElMessage.error({
      message: '下载超时，请检查网络连接',
      duration: 3000
    });
  }, 10000); // 10秒超时

  // 监听链接点击事件
  link.onclick = () => {
    // 关闭之前的消息并显示新的消息
    ElMessage.closeAll();
    ElMessage({
      message: '正在下载文件...',
      type: 'info',
      duration: 0
    });
  };

  // 触发点击事件
  link.click();

  // 模拟检测下载完成（实际项目中需要根据实际情况调整）
  const checkDownload = () => {
    // 这里应该是实际检测下载是否完成的逻辑
    // 由于浏览器安全限制，无法直接检测下载是否完成
    // 所以这里使用setTimeout模拟
    clearTimeout(timeoutId);
    ElMessage.closeAll();
    ElMessage.success({
      message: '承诺书下载成功！',
      duration: 3000
    });
    // 清理资源
    setTimeout(() => {
      document.body.removeChild(link);
    }, 100);
  };

  // 设置检测延迟（模拟网络请求时间）
  setTimeout(checkDownload, 1500);
};

// 下载完整申请表
const handleDownloadFullForm = () => {
  // 验证表单是否填写完整
  if (!formRef.value) return;

  formRef.value.validate((valid) => {
    if (valid) {
      // 表单验证通过，生成下载
      generateFullFormDownload();
    } else {
      ElMessage.warning('请先完整填写表单信息再下载');
    }
  });
};

const generateFullFormDownload = () => {
  const loadingMessage = ElMessage({
    message: '正在生成申请表...',
    type: 'info',
    duration: 0
  });

  try {
    // 创建一个新的窗口来生成打印内容
    const printWindow = window.open('', '_blank');
    if (!printWindow) {
      ElMessage.closeAll();
      ElMessage.error('请允许弹窗以下载申请表');
      return;
    }

    // 生成完整的HTML内容
    const htmlContent = generatePrintableHTML();

    printWindow.document.write(htmlContent);
    printWindow.document.close();

    // 等待内容加载完成后触发打印
    printWindow.onload = () => {
      ElMessage.closeAll();
      ElMessage.success('申请表已生成，请在新窗口中打印或保存为PDF');

      // 自动触发打印对话框
      setTimeout(() => {
        printWindow.print();
      }, 500);
    };

  } catch (error) {
    ElMessage.closeAll();
    ElMessage.error('生成申请表失败: ' + (error.message || '未知错误'));
  }
};

// 生成可打印的HTML内容
const generatePrintableHTML = () => {
  // 数字转大写金额的函数
  const toChineseCurrency = (num) => {
    if (!num || num === 0) return '零元整';
    const chineseNum = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
    const chineseUnit = ['', '拾', '佰', '仟'];
    const bigUnit = ['', '万', '亿', '兆'];
    const result = [];
    let fraction = ['角', '分'];
    let numStr = num.toString().split('.');
    let integerPart = numStr[0];
    let fractionPart = numStr.length > 1 ? numStr[1] : '';
    let temp = '';

    for (let i = 0; i < integerPart.length; i++) {
      let n = integerPart.length - i - 1;
      let unit = '';
      if (n % 4 === 0 && n !== 0 && i !== 0) {
        unit = bigUnit[n / 4 - 1];
      } else if (n % 4 > 0) {
        unit = chineseUnit[n % 4];
      }
      if (integerPart[i] !== '0') {
        temp = chineseNum[parseInt(integerPart[i])] + unit;
      } else if (temp !== '零') {
        temp = '零';
      }
      if (temp !== '零' || result[result.length - 1] !== '零') {
        result.push(temp);
      }
    }
    if (result[result.length - 1] === '零') {
      result.pop();
    }
    result.push('元');

    for (let i = 0; i < fractionPart.length && i < 2; i++) {
      if (fractionPart[i] !== '0') {
        result.push(chineseNum[parseInt(fractionPart[i])] + fraction[i]);
      }
    }
    if (result[result.length - 1] === '元') {
      result.push('整');
    }
    return result.join('');
  };

  return `
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>桂林电子科技大学科技园退租审批表</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: "Microsoft YaHei", Arial, sans-serif;
        }
        body {
            padding: 20px;
            background-color: white;
        }
        .container {
            max-width: 800px;
            margin: 0 auto;
            background-color: white;
            padding: 30px;
        }
        .header {
            text-align: center;
            margin-bottom: 30px;
        }
        .header h1 {
            font-size: 22px;
            font-weight: bold;
            margin-bottom: 10px;
            letter-spacing: 2px;
        }
        .header .no {
            text-align: right;
            font-size: 16px;
            margin-bottom: 20px;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            table-layout: fixed;
            font-size: 14px;
            border: 1px solid #000;
        }
        td {
            border: 1px solid #000;
            height: 30px;
            padding: 4px 6px;
            vertical-align: middle;
            word-break: break-all;
        }
        tr:last-child td {
            border-bottom: 1px solid #000;
        }
        td:last-child {
            border-right: 1px solid #000;
        }
        .title-cell {
            background-color: #f5f5f5;
            font-weight: bold;
            text-align: center;
        }
        .promise-content {
            line-height: 1.8;
            text-indent: 2em;
            margin-top: 20px;
            margin-bottom: 20px;
        }
        .signature {
            text-align: right;
            padding-right: 20px;
            margin-top: 20px;
            margin-bottom: 20px;
        }
        input {
            border: none;
            background: transparent;
            width: 100%;
            text-align: center;
            font-size: 14px;
        }
        @media print {
            body { padding: 0; }
            .container { padding: 0; max-width: 100%; margin: 0; }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>桂林电子科技大学科技园退租审批表</h1>
            <div class="no">NO.</div>
        </div>

        <table>
            <colgroup>
                <col style="width: 12%">
                <col style="width: 8%">
                <col style="width: 8%">
                <col style="width: 15%">
                <col style="width: 5%">
                <col style="width: 5%">
                <col style="width: 10%">
                <col style="width: 12%">
                <col style="width: 15%">
                <col style="width: 10%">
            </colgroup>

            <tr>
                <td class="title-cell">申请企业</td>
                <td colspan="5">${form.enterpriseName || ''}</td>
                <td class="title-cell">申请日期</td>
                <td colspan="3">${form.applicationDate || ''}</td>
            </tr>

            <tr>
                <td class="title-cell">房号</td>
                <td colspan="2">${form.roomNumber || ''}</td>
                <td class="title-cell">经办人</td>
                <td colspan="2">${form.contactPerson || ''}</td>
                <td class="title-cell">联系方式</td>
                <td colspan="3">${form.contactMethod || ''}</td>
            </tr>

            <tr>
                <td class="title-cell" style="height: 40px;">退租原因</td>
                <td colspan="9" style="text-align: left; padding: 8px;">${form.exitReason || ''}</td>
            </tr>

            <tr>
                <td class="title-cell">申请退租日期</td>
                <td colspan="9">${form.exitDate || ''}</td>
            </tr>

            <tr>
                <td rowspan="3" class="title-cell">退款账户明细</td>
                <td class="title-cell">户名</td>
                <td colspan="8">${form.refundAccountName || ''}</td>
            </tr>

            <tr>
                <td class="title-cell">账号</td>
                <td colspan="8">${form.refundAccountNumber || ''}</td>
            </tr>

            <tr>
                <td class="title-cell">开户行</td>
                <td colspan="8">${form.refundBank || ''}</td>
            </tr>
        </table>

        <div class="promise-content">
            <p>本公司承诺以上填报内容真实有效，截止至申请退租日期承诺做到以下两点：</p>
            <p>1、清空场地内所有物品并将原租用场地打扫干净；</p>
            <p>2、将租用场地的钥匙交给科技园相关负责老师。</p>
            <p>如超过申请退租日期1个月仍未将原租用场地清空，则视为自动放弃场地内的所有物品的所有权，桂林电子科技大学科技园有权对其进行处置。</p>
            <p>特此承诺。</p>
        </div>

        <div class="signature">
            <div style="display: flex; align-items: center; margin-bottom: 10px; justify-content: flex-end;">
                <p style="margin-right: 10px;">承诺人（公司法人）：</p>
                <span style="width: 200px; border-bottom: 1px solid #000; display: inline-block; text-align: center;">${form.applicantSignature || ''}</span>
            </div>
            <div style="display: flex; align-items: center; margin-bottom: 10px; justify-content: flex-end;">
                <p>（公司盖章）</p>
            </div>
            <div style="display: flex; align-items: center; justify-content: flex-end;">
                <p style="margin-right: 10px;">日期：</p>
                <span style="width: 200px; border-bottom: 1px solid #000; display: inline-block; text-align: center;">${form.commitmentDate || ''}</span>
            </div>
        </div>

        <table style="margin-top: 40px;">
            <colgroup>
                <col style="width: 12%">
                <col style="width: 8%">
                <col style="width: 8%">
                <col style="width: 15%">
                <col style="width: 5%">
                <col style="width: 5%">
                <col style="width: 10%">
                <col style="width: 12%">
                <col style="width: 15%">
                <col style="width: 10%">
            </colgroup>
            <tr>
                <td colspan="10" class="title-cell">科技园审批（以下内容由科技园填写）：</td>
            </tr>

            <tr>
                <td class="title-cell">履约保证金</td>
                <td class="title-cell">￥</td>
                <td colspan="2">${form.deposit || ''}</td>
                <td colspan="2" class="title-cell">大写：</td>
                <td colspan="4">${form.deposit ? toChineseCurrency(form.deposit) : ''}</td>
            </tr>

            <tr>
                <td class="title-cell">应缴款</td>
                <td colspan="2" class="title-cell">房屋租赁费￥</td>
                <td colspan="1">${form.rentalFee || ''}</td>
                <td colspan="2" class="title-cell">大写：</td>
                <td colspan="4">${form.rentalFee ? toChineseCurrency(form.rentalFee) : ''}</td>
            </tr>

            <tr>
                <td class="title-cell">应退款</td>
                <td class="title-cell">￥</td>
                <td colspan="2">${form.refundAmount || ''}</td>
                <td colspan="2" class="title-cell">大写：</td>
                <td colspan="4">${form.refundAmount ? toChineseCurrency(form.refundAmount) : ''}</td>
            </tr>

            <tr>
                <td class="title-cell">需补交款</td>
                <td class="title-cell">￥</td>
                <td colspan="2">${form.additionalPayment || ''}</td>
                <td colspan="2" class="title-cell">大写：</td>
                <td colspan="4">${form.additionalPayment ? toChineseCurrency(form.additionalPayment) : ''}</td>
            </tr>

            <tr>
                <td class="title-cell">审批</td>
                <td class="title-cell">经办人</td>
                <td colspan="2">${form.handler || ''}</td>
                <td colspan="3" class="title-cell">办公室主任核签</td>
                <td colspan="3">${form.officeDirectorSignature || ''}</td>
            </tr>
            <tr>
                <td colspan="3" class="title-cell">部门负责人</td>
                <td colspan="7">${form.departmentHeadSignature || ''}</td>
            </tr>
        </table>
    </div>
</body>
</html>
  `;
};

// 错误处理（捕获可能的异常）
window.addEventListener('unhandledrejection', (event) => {
  ElMessage.closeAll();
  ElMessage.error({
    message: '下载失败: ' + (event.reason?.message || '未知错误'),
    duration: 3000
  });
});


// 保存草稿
const saveDraft = async () => {

  const formData = form;
  try {
    let response;
    if (totalRecord.value === 1) {
      // 如果存在未提交记录，则调用更新接口
      response = await editexitApplicationForm(formData) as unknown as AjaxResult<any>;

    } else {
      // 否则调用添加接口
      response = await exitApplicationForm(formData) as unknown as AjaxResult<any>;
    }

    if (response.code === 200) {
      ElMessage.success('草稿保存成功');
      //isSubmit.value = false;
      router.push('/personal-center/graduation-or-exit/my-exit');
    } else {
      ElMessage.error('保存失败');
    }
  } catch (error) {
    console.error('保存失败:', error);
    ElMessage.error('保存失败');
  }
};
onMounted(() => {
  const id = route.query.id;
  if (id) {
    totalRecord.value=1;
    console.log(id);
    getUserDraft(Number(id)); // 页面加载时获取需要的报表数据
  }

});
</script>

<style scoped lang="scss">
.header {
  display: flex;
  justify-content: space-between;
  font-weight: bold;
  font-size: 20px;
  margin-bottom: 20px;
  resize: none;
}
.el-card {
  width: 100%;
  margin: 10px auto;
  resize: none;
}
.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  resize: none;
}
.commit {
  width: 100%;
  border: 1px solid #ccc;
  border-radius: 10px;
  padding: 30px;
  margin: 20px auto;
  resize: none;
}
</style>
